﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Mvc.Trialer;
using Mvc.Trialer.Helper;
using MvcTrialerNuGetDatabase.Models;

namespace MvcTrialerNuGetDatabase.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        [Authenticated]
        [Trial]
        public ActionResult Index()
        {
            ViewData["NickName"] = Utility.Nickname;
            return View();
        }

        [Authenticated]
        [Trial]
        public ActionResult Page2()
        {
            ViewData["NickName"] = Utility.Nickname;
            return View();
        }

        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View();
            }

            if (Utility.LogMe(model.Email, model.Password))
            {
                if (Trial.On & Utility.Expired)
                {
                    ModelState.AddModelError("Email", "Trial has expired");
                    return View();
                }
                else
                {
                    FormsAuthentication.SetAuthCookie(model.Email, false);
                    return RedirectToAction("Index");
                }
            }
            else
            {
                ModelState.AddModelError("Password", "Invalid email or password");
                return View();
            }
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return Redirect("Login");
        }
    }
}

namespace Mvc.Trialer.Helper
{
    /// <summary>
    /// Custom Action Filter to Redirect an Action if it's not authenticated
    /// </summary>
    public class AuthenticatedAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!filterContext.HttpContext.Request.IsAuthenticated)
            {
                var request = filterContext.HttpContext.Request;
                filterContext.HttpContext.Response.Redirect(string.Format("{0}://{1}{2}/Home/Login", request.Url.Scheme, request.Url.Authority, request.ApplicationPath.TrimEnd('/')));                
            }
        }
    }

    public class Utility
    {
        public static string Nickname { get; set; }
        public static bool Expired { get; set; }

        public static bool LogMe(string email, string password)
        {
            bool retval = false;
            using (DataContext dc = new DataContext())
            {
                User user = dc.Users.FirstOrDefault(x => x.Email == email);
                if (user != null)
                {
                    if (user.Password == password)
                    {
                        retval = true;
                        Nickname = user.NickName;
                        if (user.TrialDate.HasValue)
                        {
                            Trial.EndDate = user.TrialDate.Value;
                            Expired = Trial.Ended;
                            Trial.On = true;
                        }
                        else
                        {
                            Trial.On = false;
                        }
                    }
                }
            }
            return retval;
        }
    }
}